// 最后光标对象
let lastEditRange;
let $editor = $("#editor");
let $parsed = $("#parsed");
let serverPath = "http://127.0.0.1:8080";

$(function () {
  //   // 编辑器点击事件
  //   $editor.click(function (e) {
  //     // 获取选定对象
  //     let selection = getSelection();
  //     // 设置最后光标对象
  //     lastEditRange = selection.getRangeAt(0);
  //   });

  //   // 编辑器按键事件
  //   $editor.keyup(function (e) {
  //     let selection = getSelection();
  //     lastEditRange = selection.getRangeAt(0);
  //   });

  // 编辑器内容改变事件
  $editor.on("input propertychange", sendMd);

  // 滚动事件
  $editor.on("scroll", scrollSyncLeft);
  $parsed.on("scroll", scrollSyncRight);
});

/**
 * 同步滚动
 */
function scrollSyncLeft() {
  $parsed.scrollLeft($editor.scrollLeft());
  $parsed.scrollTop($editor.scrollTop());
}

function scrollSyncRight() {
  $editor.scrollLeft($parsed.scrollLeft());
  $editor.scrollTop($parsed.scrollTop());
}

/**
 * 将编辑器的内容发送到服务器
 */
function sendMd() {
  let md = parseMd($editor.val());
  let abc = 0;
  $.ajax({
    type: "post",
    url: serverPath + "/parse",
    data: { md: md },
    xhrFields: { withCredentials: true },
    success: function (response) {
      if (response.status) {
        // 成功
        $(".parsed").html(response.data);
      } else {
      }
    },
  });
}

function parseMd(html) {
  let res = html;
  res = res.replace(/\<div\>\<br\>\<\/div\>/g, "\n");
  res = res.replace(/\<div\>/g, "\n");
  res = res.replace(/\<br\>/g, "");
  res = res.replace(/\<\/div\>/g, "");
  res = res.replace(/\&nbsp;/g, " ");
  res = res.replace(/\&gt;/g, ">");
  return res;
}

function untils(choice) {
  let text = document.getElementById("editor");
  if (window.getSelection) {
    if (text.selectionStart != undefined && text.selectionEnd != undefined) {
      let changeMap = {
        i: ["*", "*", true],
        b: ["**", "**", true],
        bi: ["***", "***", true],
        u: ["<u>", "</u>", true],
        s: ["~~", "~~", true],
        h1: ["# ", "", false],
        h2: ["## ", "", false],
        h3: ["### ", "", false],
        "--": ["", "\n------------\n", false],
        ol: ["1. ", "", false],
        ul: ["- ", "", false],
      };
      if (
        (text.selectionEnd == 0 || text.selectionStart >= text.selectionEnd) &&
        changeMap[choice][2]
      ) {
        alert("未选中文字");
      } else {
        text.value =
          text.value.slice(0, text.selectionStart) +
          changeMap[choice][0] +
          text.value.slice(text.selectionStart, text.selectionEnd) +
          changeMap[choice][1] +
          text.value.slice(text.selectionEnd);
      }
    }
  }
}
